package com.beagle.njddapp.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.beagle.njddapp.R;
import com.beagle.njddapp.base.BaseApplication;
import com.beagle.njddapp.base.BaseMvpActivity;
import com.beagle.njddapp.bean.OcrIdBean;
import com.beagle.njddapp.bean.OcrIdPhotoBean;
import com.beagle.njddapp.bean.UploadBean;
import com.beagle.njddapp.bean.UserInfoBean;
import com.beagle.njddapp.core.UserService;
import com.beagle.njddapp.ui.presenter.BasicUserInfoPresenter;
import com.beagle.njddapp.ui.view.BasicUserInfoView;
import com.beagle.njddapp.utils.GlideEngine;
import com.beagle.njddapp.utils.PatternUtil;
import com.beagle.njddapp.utils.PrefsManager;
import com.beagle.njddapp.utils.StatusBarUtil;
import com.beagle.njddapp.utils.Utils;
import com.beagle.njddapp.weight.dialog.GanderDIalog;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;


import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.beagle.njddapp.core.UserService.TOKEN;

/**
 * @author hxx
 * @date 2021-03-10 19:30
 * 基础信息填写
 */
public class BasicUserInfoActivity extends BaseMvpActivity<BasicUserInfoView, BasicUserInfoPresenter> implements BasicUserInfoView {

    @BindView(R.id.ed_name)
    EditText edName;
    @BindView(R.id.ed_identity)
    EditText edIdentity;
    @BindView(R.id.ed_phone)
    TextView edPhone;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.commom_title_tv)
    TextView tvTitle;
    @BindView(R.id.rl_age)
    RelativeLayout rlAge;
    @BindView(R.id.ll_photo)
    LinearLayout llPhoto;
    @BindView(R.id.iv1)
    ImageView ivFront;
    @BindView(R.id.iv2)
    ImageView ivBAck;
    @BindView(R.id.ed_age)
    EditText edAge;
    @BindView(R.id.ed_invate)
    EditText edInvate;
    @BindView(R.id.prograssBar)
    ProgressBar progressBar;
    public static final int CHOOSE_IMG_BACK = 1002;
    public static final int CHOOSE_IMG_FRONT = 1003;
    public static final int CHOOSE_IDCARD = 1004;

    private UserInfoBean userInfoBean;
    private int gander = 1;
    private int type = -1;
    private int from;


    @Override
    public int getLayoutId() {
        return R.layout.activity_basic_userinfo;
    }

    @Override
    public void init() {
        StatusBarUtil.immersive(this, Color.WHITE);
        StatusBarUtil.darkMode(this);
        tvTitle.setText("基础信息登记");
//        if (UserService.getInstance().getRole() == UserService.ROLE_OWNER) {
            //农机主
//            llPhoto.setVisibility(View.GONE);
//            rlAge.setVisibility(View.GONE);
//        }
        from = getIntent().getIntExtra("from", -1);
        edPhone.setText(UserService.getInstance().getPhone());
        if (from == 2 && UserService.getInstance().getUserInfoBean() != null) {
            edName.setText(UserService.getInstance().getUserInfoBean().getUserName());
            edName.setClickable(false);
            edIdentity.setText(UserService.getInstance().getUserInfoBean().getIdcard());
            edIdentity.setClickable(false);
            edPhone.setText(UserService.getInstance().getUserInfoBean().getPhone());
            edPhone.setClickable(false);
            tvSex.setText(UserService.getInstance().getUserInfoBean().getGender() + "");
            tvSex.setClickable(false);
            edAge.setText(UserService.getInstance().getUserInfoBean().getDrivingAge() + "");
            edAge.setClickable(false);
            rlAge.setClickable(false);
        }
        userInfoBean = new UserInfoBean();
        userInfoBean.setUserRole(UserService.getInstance().getRole());
    }

    @Override
    public BasicUserInfoView getMvpView() {
        return this;
    }

    @Override
    public BasicUserInfoPresenter createPresenter() {
        return new BasicUserInfoPresenter();
    }

    @Override
    public void onError(String message) {
        ToastUtils.showShort(message);
        progressBar.setVisibility(View.GONE);
    }

    @OnClick({R.id.common_back_iv, R.id.tv_sex, R.id.iv1, R.id.iv2, R.id.tv_next,R.id.btn_scan})
    public void onCLick(View view) {
        switch (view.getId()) {
            case R.id.common_back_iv:
                onBackPressed();
                break;
            case R.id.tv_sex:
                change_sex();
                break;
            case R.id.btn_scan:
                Matisse.from(BasicUserInfoActivity.this)
                        .choose(MimeType.ofImage())
                        .capture(true)
                        .countable(true)
                        .maxSelectable(1)
                        .thumbnailScale(0.85f)
                        .captureStrategy(new CaptureStrategy(true, "com.beagle.njddapp"))
                        .imageEngine(GlideEngine.getInstance())
                        .showPreview(false) // Default is `true`
                        .forResult(CHOOSE_IDCARD);
                break;
            case R.id.iv1:
                Matisse.from(BasicUserInfoActivity.this)
                        .choose(MimeType.ofImage())
                        .capture(true)
                        .countable(true)
                        .maxSelectable(1)
                        .thumbnailScale(0.85f)
                        .captureStrategy(new CaptureStrategy(true, "com.beagle.njddapp"))
                        .imageEngine(GlideEngine.getInstance())
                        .showPreview(false) // Default is `true`
                        .forResult(CHOOSE_IMG_FRONT);

                break;
            case R.id.iv2:
                Matisse.from(BasicUserInfoActivity.this)
                        .choose(MimeType.ofImage())
                        .capture(true)
                        .countable(true)
                        .maxSelectable(1)
                        .thumbnailScale(0.85f)
                        .captureStrategy(new CaptureStrategy(true, "com.beagle.njddapp"))
                        .imageEngine(GlideEngine.getInstance())
                        .showPreview(false) // Default is `true`
                        .forResult(CHOOSE_IMG_BACK);
                break;
            case R.id.tv_next:
                String name = edName.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort("请输入正确的姓名");
                    return;
                }

                String sex = tvSex.getText().toString();
                if (TextUtils.isEmpty(sex) ) {
                    ToastUtils.showShort("请选择性别");
                    return;
                }
                userInfoBean.setUserName(edName.getText().toString());
                userInfoBean.setIdcard(edIdentity.getText().toString());
                userInfoBean.setGender(gander);
                userInfoBean.setInvitationCode(edInvate.getText().toString());
                if (!TextUtils.isEmpty(edAge.getText().toString())) {
                    userInfoBean.setDrivingAge(Integer.parseInt(edAge.getText().toString()));
                }
                progressBar.setVisibility(View.VISIBLE);
                String identity = edIdentity.getText().toString();
                if (TextUtils.isEmpty(identity)) {
//                    if (TextUtils.isEmpty(userInfoBean.getInvitationCode())){
                        presenter.information(userInfoBean);
//                    }else {
//                        presenter.queryUserInfo(userInfoBean);
//                    }
                }else {
                    presenter.ocrCardNumber(edIdentity.getText().toString(),edName.getText().toString());
                }
                break;
        }
    }

    public void change_sex() {
        GanderDIalog ganderDIalog = new GanderDIalog(this);
        ganderDIalog.setOnGanderChooseCallBack(new GanderDIalog.onGanderChooseCallBack() {
            @Override
            public void onGanderChoose(int gander_dia) {
                if (gander_dia == 1) {
                    tvSex.setText("男");
                } else {
                    tvSex.setText("女");
                }
                gander = gander_dia;
            }
        });
        ganderDIalog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (requestCode == CHOOSE_IMG_FRONT) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            if (mSelected != null && mSelected.size() > 0) {
                type = 1;
                String path=Utils.getPathFromUri(getApplicationContext(), mSelected.get(0));
                progressBar.setVisibility(View.VISIBLE);
                presenter.ocrJsz(path,"face");
//                Glide.with(this).load(mSelected.get(0)).into(ivFront);
//                presenter.upload(Utils.getPathFromUri(getApplicationContext(), mSelected.get(0)));
            }
        } else if (requestCode == CHOOSE_IMG_BACK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            if (mSelected != null && mSelected.size() > 0) {
                type = 2;
                String path=Utils.getPathFromUri(getApplicationContext(), mSelected.get(0));
//                presenter.ocrJsz(path,"back");
                Glide.with(this).load(mSelected.get(0)).into(ivBAck);
                presenter.upload(Utils.getPathFromUri(getApplicationContext(), mSelected.get(0)));
            }
        } else if (requestCode == CHOOSE_IDCARD && data != null) {
            // 返回扫描图片地址
            List<Uri> mSelected = Matisse.obtainResult(data);
            if (mSelected != null && mSelected.size() > 0) {
                String path=Utils.getPathFromUri(getApplicationContext(), mSelected.get(0));
                progressBar.setVisibility(View.VISIBLE);
                presenter.ocr(path);

            }
        }
    }



//    private boolean isFirst = true;

    @Override
    public void toMian() {
        progressBar.setVisibility(View.GONE);
//        if (isFirst) {
//            presenter.firstRequest();
//        }
//        isFirst = false;
        ActivityUtils.finishAllActivities();
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    @Override
    public void UploadSuccess(UploadBean data) {
        progressBar.setVisibility(View.GONE);
        if (type == 1) {
            userInfoBean.setLicenceUrlA(data.getVisitURL());
        } else {
            userInfoBean.setLicenceUrlB(data.getVisitURL());
        }
    }

    @Override
    public void showIdCard(OcrIdPhotoBean ocrIdCardBean) {
        progressBar.setVisibility(View.GONE);
        OcrIdPhotoBean.ResultBean resultBean=ocrIdCardBean.getResult();
        if (resultBean==null||TextUtils.isEmpty(resultBean.getName())){
            ToastUtils.showShort("身份证信息识别失败，请上传清晰的身份证正面照片");
        }else {
            ToastUtils.showShort("身份证识别成功");
            edName.setText(resultBean.getName());
            edIdentity.setText(resultBean.getIdcardno());
            tvSex.setText(resultBean.getSex());
            if ("女".equals(resultBean.getSex())){
                gander=2;
            }else {
                gander=1;
            }
        }
    }

    @Override
    public void showIdInfo(OcrIdBean ocrIdCardBean) {
        if (ocrIdCardBean.getError_code()==0){
            OcrIdBean.ResultBean resultBean=ocrIdCardBean.getResult();
            if (resultBean.isIsok()){
                if ("女".equals(resultBean.getIdCardInfor().getSex())){
                    userInfoBean.setGender(2);
                }else {
                    userInfoBean.setGender(1);
                }
                progressBar.setVisibility(View.VISIBLE);
                if (TextUtils.isEmpty(userInfoBean.getInvitationCode())){
                    presenter.information(userInfoBean);
                }else {
                    presenter.queryUserInfo(userInfoBean);
                }

            }else {
                progressBar.setVisibility(View.GONE);
                ToastUtils.showShort("身份证验证失败,请输入和此身份证号码匹配的姓名");
            }
        }else {
            progressBar.setVisibility(View.GONE);
            ToastUtils.showShort("身份证验证失败,请输入真实的身份证号码和姓名");

        }

    }

    @Override
    public void showJszSuccess(String path) {
        type = 1;
        Glide.with(this).load(path).into(ivFront);
        presenter.upload(path);
    }

    @Override
    public void toRole() {
        progressBar.setVisibility(View.GONE);
        ActivityUtils.finishAllActivities();
        startActivity(new Intent(this, ChooseRoleActivity.class));
        finish();
    }

    @Override
    public void onBackPressed() {
        tipClick(tvTitle);
    }

    /**
     * 提示对话框
     *
     * @param view
     */
    public void tipClick(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("您还没有完善信息，确定退出吗");
        //点击对话框以外的区域是否让对话框消失
        builder.setCancelable(true);
        //设置正面按钮
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (from == 2) {
                    System.exit(0);
                } else if (from==1){
                    finish();
                }else {
                    exit();
                }
            }
        });
        //设置反面按钮
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        //显示对话框
        dialog.show();
    }
    public void exit(){
        UserService.getInstance().setUserInfoBean(null);
        UserService.getInstance().setRole(-1);
        UserService.getInstance().setToken("");
        UserService.getInstance().setPhone("");
        PrefsManager.getInstance(BaseApplication.getInstance()).putString(TOKEN,"");
        PrefsManager.getInstance(getApplicationContext()).clear();
        tvSex.postDelayed(new Runnable() {
            @Override
            public void run() {
                ActivityUtils.finishAllActivities();
                System.exit(0);
            }
        },1000);
    }
}
